package com.yunshipei.ui.fragment;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.yunshipei.adapter.MyListViewAdapter;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.UserInfo;
import com.yunshipei.enterplorer.R;
import com.yunshipei.inter.ContactsRefreshCallBack;
import com.yunshipei.model.FrequentContacts;
import com.yunshipei.model.ListAndGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.app.model.UserInfoByUserId;

/**
 * 公司组织架构
 *
 * @author cike
 */
@SuppressLint("ValidFragment")
public class DepartmentFragment extends Fragment {

    private static final String ARGS_DATA_BOOL = "com.enterplorer.data.bool";

    private ListView listview;
    private MyListViewAdapter adapter;
    private String parentName;
    private boolean isFirstCreate = true;
    private ContactsRefreshCallBack callBack;

    public static DepartmentFragment newInstances(boolean bool) {
        DepartmentFragment departmentFragment = new DepartmentFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(ARGS_DATA_BOOL, bool);
        departmentFragment.setArguments(bundle);
        return departmentFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.isFirstCreate = getArguments().getBoolean(ARGS_DATA_BOOL);
        fetchDepartmentData();
    }

    public void fetchDepartmentData() {
        SharedPreferences sp = YspPreferences.getInstance().getSharedPreferences();
        String departId = sp.getString("topId", "");
        String companyId = sp.getString("companyId", "");
        if (isFirstCreate) {
            setDepartmentId(departId, companyId, "全公司");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list, container, false);
        listview = (ListView) view.findViewById(R.id.listView1);
        if (adapter == null) {
            adapter = new MyListViewAdapter(getActivity(), parentName);
        }
        listview.setAdapter(adapter);
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                System.out.println("firstVisibleItem = " + firstVisibleItem + "     visibleItemCount =" + visibleItemCount
                        + "totalItemCount" + totalItemCount + "\n lastVisible=" + (firstVisibleItem + visibleItemCount));

            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (callBack != null) {
            listview.setTag(1);
            callBack.setChildFragmentListView(listview);
        }
    }

    public void setDepartmentId(String departId, String companyId, String parent) {
        parentName = parent;
        HttpMethods.getInstance().fetchDepartment(departId, companyId, new DepartmentSubscriber());
    }

    private class DepartmentSubscriber extends BaseSubscriberAdapter<FrequentContacts> {
        @Override
        public void onNext(FrequentContacts frequentContact) {
            ListAndGroup listAndGroup = frequentContact.getData();
            if (listAndGroup == null) {
                return;
            }
            if (adapter == null) {
                adapter = new MyListViewAdapter(getActivity(), parentName);
            }
            adapter.updateListView(listAndGroup);
            List<UserInfo> members = frequentContact.getData().getMembers();
            int size = members.size();
            Map<String, io.rong.imlib.model.UserInfo> map = new HashMap<>();
            for (int i = 0; i < size; i++) {
                io.rong.imlib.model.UserInfo user = new io.rong.imlib.model.UserInfo(
                        members.get(i).getUuid(), members.get(i).getName(),
                        null);
                map.put(members.get(i).getUuid(), user);
            }
            UserInfoByUserId.getInstance().insertUserInfo(map);
            if (callBack != null) {
                callBack.setDepartmentRefreshFinished(true);
            }
        }

        @Override
        public void onError(String errorMessage) {
            if (callBack != null) {
                callBack.setDepartmentRefreshFinished(true);
            }
        }
    }

    public MyListViewAdapter getAdapter() {
        return adapter;
    }

    public void setRefreshCallBack(ContactsRefreshCallBack callBack) {
        this.callBack = callBack;
    }

}
